<!--
 * @Description: 
 * @Author: shizhe
 * @Date: 2022-04-13 10:35:44
 * @LastEditTime: 2022-07-04 12:45:40
 * @LastEditors: shizhe
 * @Reference: 
-->
<template>
  <div id="product">
    <header class="product_header">
      <div class="tip">
        <i class="iconfont icon-tishi1"></i>
        <span style="margin-left: 10px">已启用的产品将在供应商首页展示</span>
      </div>
      <el-button icon="iconfont icon-jiufuqianbaoicon06" size="mini" class="exportBtn add" @click="addProduct">
        添加产品
      </el-button>
    </header>

    <main class="product_main">
      <div class="tables">
        <el-table
          :data="tableData"
          class="table"
          height="100%"
          tooltip-effect="light"
          ref="jdjgTable"
          :header-cell-style="{
            padding: '0px',
            background: 'linear-gradient(0deg, #F4F6F9, #EAECF4, #F3F6F9)'
          }"
          :row-class-name="tabRowClassName"
          header-row-class-name="mapTable_th"
        >
          <el-table-column width="60" align="center" type="index" label="序号">
            <el-table-column width="60" align="center" type="index" label="检索">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="产品名称" align="center" width="180">
            <el-table-column width="180" align="center" prop="productName" show-overflow-tooltip>
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox no_sort" @click.stop>
                  <el-input
                    v-model.trim="infoFrom.productName"
                    @change="getData"
                    placeholder="请输入产品名称"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="价格(元)" align="center" width="150">
            <el-table-column width="150" align="center" prop="productPrice">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox no_sort" @click.stop>
                  <el-input
                    v-model.trim="infoFrom.productPrice"
                    @change="priceChange"
                    placeholder="请输入价格"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="服务区域" align="center" width="180">
            <el-table-column width="180" align="center" prop="serviceArea" show-overflow-tooltip>
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox no_sort" @click.stop>
                  <el-input
                    v-model.trim="infoFrom.serviceArea"
                    @change="getData"
                    placeholder="请输入服务区域"
                  ></el-input>
                </div>
              </template>
              <!-- <template slot-scope="scope">
                <tool-tip-node :isSetWidth="true" :value="scope.row.serviceArea" :oneLine="true"></tool-tip-node>
              </template> -->
            </el-table-column>
          </el-table-column>
          <el-table-column label="默认规格" align="center" width="180">
            <el-table-column width="180" align="center" prop="defaultSpecification" show-overflow-tooltip>
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox no_sort" @click.stop>
                  <el-input
                    v-model.trim="infoFrom.defaultSpecification"
                    @change="getData"
                    placeholder="请输入默认规格"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="备注" align="center" width="180">
            <el-table-column width="180" align="center" prop="remark" show-overflow-tooltip> </el-table-column>
          </el-table-column>
          <el-table-column label="创建人" align="center" width="180">
            <el-table-column width="180" align="center" prop="createBy" show-overflow-tooltip>
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox no_sort" @click.stop>
                  <el-input v-model.trim="infoFrom.createBy" @change="getData" placeholder="请输入创建人"></el-input>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="180">
            <el-table-column width="180" align="center" prop="createTime"> </el-table-column>
          </el-table-column>
          <el-table-column label="状态" align="center" width="120">
            <el-table-column align="center" prop="status" width="120">
              <template slot="header" align="center" slot-scope="{}">
                <div class="searchBox no_sort" @click.stop>
                  <el-select v-model.trim="infoFrom.status" placeholder="请选择" @change="getData">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="已启用" :value="1"></el-option>
                    <el-option label="已停用" :value="0"></el-option>
                  </el-select>
                </div>
              </template>
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.status">已启用</span>
                  <span v-else>已停用</span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="270">
            <el-table-column align="center" width="270">
              <template slot-scope="scope">
                <div class="">
                  <el-button
                    v-if="scope.row.status"
                    type="text"
                    class="ty czBtn"
                    size="small"
                    @click="handleClick('停用', scope.row)"
                  >
                    停用
                  </el-button>
                  <el-button v-else type="text" class="xg czBtn" size="small" @click="handleClick('启用', scope.row)">
                    启用
                  </el-button>
                  <el-button type="text" class="xg czBtn" size="small" @click="handleClick('查看', scope.row)">
                    查看
                  </el-button>
                  <el-button type="text" class="xg czBtn" size="small" @click="handleClick('修改', scope.row)">
                    修改
                  </el-button>
                  <el-button type="text" class="ty czBtn" size="small" @click="handleClick('删除', scope.row)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
      <element-pagination :Total="total" @getData="getPagChange"></element-pagination>
    </main>

    <el-dialog
      width="800px"
      v-if="visible"
      :center="true"
      :close-on-click-modal="false"
      :title="title"
      :before-close="closeDialog"
      :visible.sync="visible"
    >
      <h1>基本信息</h1>
      <el-form label-width="100px" class="addFrom">
        <el-form-item label="产品名称:" required>
          <el-input
            v-model="form.productName"
            style="width: 396px"
            size="small"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格:" required style="margin-bottom: 16px">
          <el-input
            v-model="form.productPrice"
            style="width: 396px; margin-right: 6px"
            size="small"
            placeholder="请输入价格"
          >
            <p slot="suffix" style="color: #333">元</p>
          </el-input>
        </el-form-item>
        <el-form-item label="服务区域:" required style="margin-bottom: 20px">
          <el-input
            type="textarea"
            placeholder="请输入支持该产品贸易及售后的省、市或者区县"
            v-model="form.serviceArea"
            maxlength="400"
            :autosize="{ minRows: 5 }"
          >
          </el-input>
          <span class="input_count">{{ serviceAreaCount }}</span>
        </el-form-item>
        <el-form-item label="默认规格:" required style="margin-bottom: 20px">
          <el-input
            type="textarea"
            placeholder="请输入默认规格"
            v-model="form.defaultSpecification"
            :autosize="{ minRows: 3 }"
            maxlength="200"
          >
          </el-input>
          <span class="input_count">{{ defaultSpecificationCount }}</span>
        </el-form-item>
        <el-form-item label="备注:" style="margin-bottom: 20px">
          <el-input
            type="textarea"
            placeholder="请输入备注"
            v-model="form.remark"
            :autosize="{ minRows: 3 }"
            maxlength="200"
          >
          </el-input>
          <span class="input_count">{{ remarkCount }}</span>
        </el-form-item>
        <el-form-item label="产品描述:" required style="margin-bottom: 16px">
          <el-input
            type="textarea"
            placeholder="请输入产品描述"
            v-model="form.productDescription"
            :autosize="{ minRows: 3 }"
            maxlength="200"
          >
          </el-input>
          <span class="input_count">{{ productDescriptionCount }}</span>
        </el-form-item>
        <el-form-item label="产品效果图:" required style="margin-bottom: 0">
          <el-button size="small" class="commonBtn" @click="uploadClick"> 上传图片 </el-button>
          <div style="color: #fa7355; font-size: 14px; line-height: 14px; margin-top: 6px; margin-bottom: 20px">
            上传2M以下（png、jpg、jpeg）图片，至少一张，最多不超过10张
          </div>

          <div v-if="form.productUrlList.length" class="img_box">
            <div
              v-for="(item, index) in form.productUrlList"
              :key="index"
              class="img_item"
              :style="{ marginRight: (index + 1) % 4 == 0 ? '0' : '30px' }"
            >
              <i class="iconfont icon-jiufuqianbaoicon08" @click="imgRemove(index)"></i>
              <div class="img_wrap">
                <div class="is_cover" v-if="item.cover">封面</div>
                <div class="set_cover" v-else @click="setImgCover(index)">设为封面</div>
                <div style="border: 1px solid #999; border-radius: 5px; box-sizeing: border-box">
                  <el-image style="width: 126px; height: 126px" :src="item.fileAddress"></el-image>
                </div>
              </div>
              <div style="line-height: 20px; text-align: center">
                <tool-tip-node :oneLine="true" :value="item.fileName"></tool-tip-node>
              </div>
            </div>
          </div>

          <div class="upload-photo">
            <el-upload
              class="photo-demo"
              :headers="loadHeader"
              multiple
              :limit="10"
              accept=".jpg,.png,.jpeg"
              :action="urlUpload"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :on-exceed="uploadExceed"
              :file-list="fileList"
            >
              <template slot="trigger">
                <div ref="biddUpload"></div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button size="small" class="commonBtn" @click="close">取消</el-button>
        <el-button size="small" class="commonBtn1" @click="sureBtn">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="800px"
      v-if="checkVisible"
      :center="true"
      :close-on-click-modal="false"
      title="查看产品详情"
      :before-close="closeDialog"
      :visible.sync="checkVisible"
    >
      <h1>基本信息</h1>
      <el-form label-width="100px" class="checkFrom">
        <el-form-item label="产品名称:">
          <span>{{ form.productName }}</span>
        </el-form-item>
        <el-form-item label="价格:">
          {{ form.productPrice + '元' }}
        </el-form-item>
        <el-form-item label="服务区域:" style="margin-bottom: 20px">
          <span>{{ form.serviceArea }}</span>
        </el-form-item>
        <el-form-item label="默认规格:" style="margin-bottom: 20px">
          <span>{{ form.defaultSpecification }}</span>
        </el-form-item>
        <el-form-item label="备注:" style="margin-bottom: 20px">
          <span>{{ form.remark }}</span>
        </el-form-item>
        <el-form-item label="产品描述:">
          <span>{{ form.productDescription }}</span>
        </el-form-item>
        <el-form-item label="产品效果图:" style="margin-bottom: 0">
          <div v-if="form.productUrlList.length" class="img_box">
            <div
              v-for="(item, index) in form.productUrlList"
              :key="index"
              class="img_item"
              :style="{ marginRight: (index + 1) % 4 == 0 ? '0' : '30px' }"
            >
              <div class="img_wrap">
                <div class="is_cover" v-if="item.cover">封面</div>
                <div style="border: 1px solid #999; border-radius: 5px">
                  <el-image style="width: 126px; height: 126px" :src="item.fileAddress"></el-image>
                </div>
              </div>
              <div style="line-height: 20px; text-align: center">
                <tool-tip-node :oneLine="true" :value="item.fileName"></tool-tip-node>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import ElementPagination from '../../../components/ElementPagination.vue'
import ToolTipNode from '../../../components/ToolTipNode.vue'
export default {
  components: { ElementPagination, ToolTipNode },
  data() {
    return {
      urlUpload: this.GLOBAL.weburl + '/api/file/upload',
      total: 0,
      page: 1,
      size: 15,
      tableData: [],
      visible: false,
      checkVisible: false,
      title: '',
      num: 0,
      timer: null,
      infoFrom: {
        createBy: '',
        defaultSpecification: '',
        status: null,
        productName: '',
        productPrice: '',
        serviceArea: ''
      },
      fileSuccess: true,
      form: {},
      fileList: []
    }
  },
  computed: {
    loadHeader() {
      let token = this.common.getCookie('materialsToken')
      const header = {}
      header[this.GLOBAL.tokenName] = token
      return header
    },
    serviceAreaCount() {
      let length = 0
      for (let i = 0; i < this.form.serviceArea.length; i++) {
        let flag = /[\u4e00-\u9fa5]/.test(this.form.serviceArea[i])
        if (flag) {
          length += 2
        } else {
          length += 1
        }
        if (length > 400) {
          this.form.serviceArea = this.form.serviceArea.substring(0, i)
          length -= flag ? 2 : 1
        } else if (length == 400) {
          this.form.serviceArea = this.form.serviceArea.substring(0, i + 1)
        }
      }

      return length + '/400'
    },
    defaultSpecificationCount() {
      let length = 0
      for (let i = 0; i < this.form.defaultSpecification.length; i++) {
        let flag = /[\u4e00-\u9fa5]/.test(this.form.defaultSpecification[i])
        if (flag) {
          length += 2
        } else {
          length += 1
        }
        if (length > 200) {
          this.form.defaultSpecification = this.form.defaultSpecification.substring(0, i)
          length -= flag ? 2 : 1
        } else if (length == 200) {
          this.form.defaultSpecification = this.form.defaultSpecification.substring(0, i + 1)
        }
      }

      return length + '/200'
    },
    remarkCount() {
      let length = 0
      for (let i = 0; i < this.form.remark.length; i++) {
        let flag = /[\u4e00-\u9fa5]/.test(this.form.remark[i])
        if (flag) {
          length += 2
        } else {
          length += 1
        }
        if (length > 200) {
          this.form.remark = this.form.remark.substring(0, i)
          length -= flag ? 2 : 1
        } else if (length == 200) {
          this.form.remark = this.form.remark.substring(0, i + 1)
        }
      }

      return length + '/200'
    },
    productDescriptionCount() {
      let length = 0
      for (let i = 0; i < this.form.productDescription.length; i++) {
        let flag = /[\u4e00-\u9fa5]/.test(this.form.productDescription[i])
        length += flag ? 2 : 1
        if (length > 200) {
          this.form.productDescription = this.form.productDescription.substring(0, i)
          length -= flag ? 2 : 1
        } else if (length == 200) {
          this.form.productDescription = this.form.productDescription.substring(0, i + 1)
        }
      }

      return length + '/200'
    }
  },
  mounted() {
    this.initValue()
    this.getData()
  },
  methods: {
    priceChange() {
      const regular = /^[0]*\d*(\.\d{0,2})?$/
      if (this.infoFrom.productPrice && !regular.test(this.infoFrom.productPrice)) {
        this.$message.error('请输入数字,最多两位小数')
        this.infoFrom.productPrice = ''
        return
      }
      this.getData()
    },
    handleClick(val, scope) {
      if (val == '停用' || val == '启用') {
        this.statusChange(val, scope.id)
      } else if (val == '删除') {
        this.removeProduct(scope.id)
      } else {
        this.getDetailProduct(scope.id, val)
      }
    },
    removeProduct(id) {
      this.$confirm('是否删除该产品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$https({
          method: 'post',
          url: '/product/delProduct?id=' + id
        })
          .then(res => {
            if (res.code == 0) {
              this.$message.success('删除产品信息成功')
              this.getData()
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    statusChange(val, id) {
      this.$https({
        method: 'post',
        url: '/product/updStatus',
        data: {
          id,
          status: val == '停用' ? 0 : 1
        }
      })
        .then(res => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.getData()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    sureBtn() {
      if (!this.fileSuccess) {
        this.$message.error('请等待文件上传完毕')
        return
      }
      this.form = this.common.removeSpace(this.form)
      let msg = ''
      const keyArr = [
        { label: '产品名称', value: 'productName' },
        { label: '价格', value: 'productPrice' },
        { label: '服务区域', value: 'serviceArea' },
        { label: '默认规格', value: 'defaultSpecification' },
        { label: '产品描述', value: 'productDescription' },
        { label: '产品效果图', value: 'productUrlList' }
      ]
      for (let i = 0; i < keyArr.length; i++) {
        if (!this.form[keyArr[i].value]) {
          msg = keyArr[i].label + '不能为空'
          break
        } else {
          if (keyArr[i].label == '产品效果图') {
            if (!this.form[keyArr[i].value].length) {
              msg = '请上传产品效果图'
              break
            } else {
              msg = ''
            }
          } else if (keyArr[i].label == '价格') {
            const regular = /^[0]*\d{1,9}(\.\d{0,2})?$/
            msg = regular.test(this.form[keyArr[i].value]) ? '' : '请输入正确的价格，最多9位数，2位小数'
            if (!msg) continue
            this.form[keyArr[i].value] = ''
            break
          }
        }
      }
      if (msg) {
        this.$message.error(msg)
        return
      }
      this.saveProduct()
    },
    saveProduct() {
      let url = '/product/addProduct'
      if (this.form.id) {
        url = '/product/updProduct'
      }
      this.$https({
        method: 'post',
        url,
        data: this.form
      })
        .then(res => {
          if (res.code == 0) {
            if (this.title == '添加产品') {
              this.$message.success('添加产品信息成功')
            } else {
              this.$message.success('修改产品信息成功')
            }
            this.close()
            this.getData()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getDetailProduct(id, val) {
      this.$https({
        method: 'post',
        url: '/product/getDetail?id=' + id
      })
        .then(res => {
          if (res.code == 0) {
            this.form = JSON.parse(JSON.stringify(res.data))
            this.form.productPrice = res.data.productPrice + ''
            if (val == '修改') {
              this.visible = true
              this.title = '修改产品'
              this.fileList = [...this.form.productUrlList]
              this.num = this.form.productUrlList.length || 0
            } else {
              this.checkVisible = true
            }
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    closeDialog(done) {
      this.initValue()
      done()
    },
    initValue() {
      this.form = {
        defaultSpecification: '',
        productDescription: '',
        productName: '',
        productPrice: '',
        remark: '',
        serviceArea: '',
        productUrlList: []
      }
      this.fileList = []
      this.num = 0
      this.fileSuccess = true
      this.title = ''
    },
    close() {
      this.visible = false
      this.initValue()
    },
    tabRowClassName({ row, rowIndex }) {
      let index = rowIndex + 1
      if (index % 2 == 0) {
        return 'warning-row'
      }
    },
    // 设置图片为封面
    setImgCover(index) {
      this.form.productUrlList.forEach(item => {
        this.$set(item, 'cover', false)
      })
      this.$set(this.form.productUrlList[index], 'cover', true)
    },
    imgRemove(index) {
      this.form.productUrlList.splice(index, 1)
      console.log(1)
      console.log(this.form.productUrlList)
      this.fileList.splice(index, 1)
      this.num = this.fileList.length
      if (this.form.productUrlList.length) {
        const flag = this.form.productUrlList.some(item => {
          return item.cover == true
        })
        if (!flag) this.$set(this.form.productUrlList[0], 'cover', true)
      }
    },
    uploadClick() {
      this.$refs.biddUpload.click()
    },
    uploadSuccess(val, e, el) {
      if (e.response.code != 0) {
        this.$message.error(e.response.msg)
        return false
      }
      this.num++
      if (this.num == el.length) {
        this.num = el.length
        this.fileSuccess = true
        if (el.length > 1) {
          const flag = this.form.productUrlList.some(item => {
            return item.cover == true
          })
          if (!flag) this.$set(this.form.productUrlList[0], 'cover', true)
        }
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.$message.success('上传成功')
      }, 200)
      this.fileList = el
      this.form.productUrlList.push({
        fileAddress: e.response.data,
        fileName: e.name,
        cover: false
      })
      if (el.length == 1) {
        this.$set(this.form.productUrlList[0], 'cover', true)
      }
    },
    beforeUpload(file) {
      // 文件未上传完毕不能提交
      this.fileSuccess = false
      const isLt = file.size / 1024 / 1024 / 2 <= 1
      if (!isLt) {
        this.$message.error('单张图片大小不能超过2m,请检查文件大小并重新尝试')
      }
      return isLt
    },
    uploadExceed() {
      this.$message.error('最多上传10张产品效果图')
    },
    addProduct() {
      this.title = '添加产品'
      this.visible = true
    },
    getPagChange(data) {
      this.page = data.currentPage
      this.size = data.pagesize
      this.getData()
    },
    getData() {
      this.$https({
        method: 'post',
        url: '/product/getList',
        data: { ...this.infoFrom, page: this.page, size: this.size }
      })
        .then(res => {
          if (res.code == 0) {
            this.tableData = res.data.records || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="less" scoped>
#product {
  height: 100%;
  padding: 16px 16px 40px;
  box-sizing: border-box;
  .product_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tip {
      color: #fa7355;
      font-size: 16px;
      .icon-tishi1 {
        font-size: 16px;
      }
    }
  }
  .product_main {
    padding-top: 16px;
    box-sizing: border-box;
    height: calc(100% - 32px);
    .tables {
      height: calc(100% - 62px);
    }
  }
  .add {
    width: 114px;
    height: 32px;
    border: 1px solid #fa7355;
    border-radius: 5px;
  }
  h1 {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    padding-left: 10px;
    border-left: 4px solid #fa7355;
    span {
      font-weight: normal;
      color: #999;
    }
  }
  .xg {
    color: #166df1;
  }
  .ty {
    color: #ff3d3d;
  }
  .addFrom {
    margin-top: 16px;
    .el-form-item {
      margin-bottom: 12px;
    }
    /deep/.el-input__count {
      line-height: 1;
    }
    /deep/ .el-textarea__inner {
      padding-bottom: 10px;
    }
    .input_count {
      position: absolute;
      right: 16px;
      bottom: 2px;
      line-height: 1;
      color: #8e8e8e;
      font-size: 14px;
    }
  }
  .checkFrom {
    margin-top: 20px;
    .el-form-item {
      margin-bottom: 20px;
    }
    /deep/ .el-form-item__content,
    /deep/ .el-form-item__label {
      line-height: 1;
    }
  }
  .img_box {
    display: flex;
    flex-wrap: wrap;
  }
  .img_item {
    width: 128px;
    margin-right: 30px;
    margin-bottom: 20px;
    line-height: 0;
    position: relative;
    .icon-jiufuqianbaoicon08 {
      position: absolute;
      font-size: 24px;
      color: red;
      z-index: 10;
      cursor: pointer;
      top: 0px;
      right: -12px;
      line-height: 0;
    }
    .img_wrap {
      position: relative;
      width: 100%;
      .is_cover {
        position: absolute;
        text-align: center;
        line-height: 24px;
        color: #fff;
        font-size: 14px;
        z-index: 9;
        width: 100%;
        height: 24px;
        background: rgba(0, 0, 0, 0.55);
        border-radius: 5px;
        top: 0;
      }
      .set_cover {
        position: absolute;
        cursor: pointer;
        bottom: 0;
        height: 24px;
        background: rgba(0, 0, 0, 0.55);
        border-radius: 5px;
        width: 100%;
        z-index: 9;
        text-align: center;
        line-height: 24px;
        color: #fff;
        font-size: 14px;
      }
    }
  }
  .upload-photo {
    display: none;
  }
  .footer {
    text-align: center;
    margin-top: 20px;
  }
}
</style>
